package com.ganmiao.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ganmiao.exception.DefaultBusinessException;
import com.ganmiao.resp.ResponseCode;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @Author zero.yin
 * @Date 2022/8/6 4:02 PM
 * @Desc poi工具类
 */
@Log4j2
public class POIUtil {
    public static void handleExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error(String.format("导出[%s]Excel异常：[%s]", fileName, e.getMessage()), e);
            throw new DefaultBusinessException(String.format("导出[%s]Excel异常", fileName), ResponseCode.FAIL);
        }
    }

    public static String getCellValue(Workbook wb, Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            return getCellValueOfDouble(cell.getNumericCellValue());
        }
        if (cell.getCellType() == CellType.STRING) {
            String str1 = cell.getStringCellValue();
            String str2 = str1.replaceAll(" ", "");
            String str3 = str2.replaceAll("\n", "");
            return str3;
        }
        if (cell.getCellType() == CellType.BLANK) {
            return null;
        }
        throw new DefaultBusinessException(String.format("行[%s]数据不合法！", cell.getRowIndex()));
    }

    public static String getCellValueNoException(Workbook wb, Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == CellType.NUMERIC) {
            return getCellValueOfDouble(cell.getNumericCellValue());
        }
        if (cell.getCellType() == CellType.STRING) {
            String str1 = cell.getStringCellValue();
            String str2 = str1.replaceAll(" ", "");
            return str2;
        }
        return null ;
        //throw new DefaultBusinessException(String.format("行[%s]数据不合法！", cell.getRowIndex()));
    }

    private static String getCellValueOfDouble(Double d) {
        String doubleStr = d.toString();
        boolean b = doubleStr.contains("E");
        int indexOfPoint = doubleStr.indexOf('.');
        if (b) {
            int indexOfE = doubleStr.indexOf('E');
            BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
                    + BigInteger.ONE.intValue(), indexOfE));
            int pow = Integer.valueOf(doubleStr.substring(indexOfE
                    + BigInteger.ONE.intValue()));
            int xsLen = xs.toByteArray().length;
            int scale = xsLen - pow > 0 ? xsLen - pow : 0;
            doubleStr = String.format("%." + scale + "f", d);
        } else {
            Pattern p = Pattern.compile(".0$");
            java.util.regex.Matcher m = p.matcher(doubleStr);
            if (m.find()) {
                doubleStr = doubleStr.replace(".0", "");
            }
        }
        return doubleStr;
    }

    /**
     * 判断是否空行
     *
     * @param row
     * @return
     * @author：yinls
     */
    @SuppressWarnings("deprecation")
    public static boolean isRowEmpty(Row row) {
        if (Objects.isNull(row) || row.toString().isEmpty()) {
            return true;
        }
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            row.getCell(i).setCellType(CellType.STRING);
            Cell cell = row.getCell(i);
            String trim = cell.getStringCellValue().trim();
            trim = trim.replaceAll(" ", "");
            if (StringUtils.isEmpty(trim)) {
                return true;
            }
            if (cell.getCellType() != CellType.BLANK) {
                return false;
            }

        }
        return true;
    }


}
